<?php
namespace control;
/*
*生产区域登记
*/

class productionAreaClass extends adIndexClass
{
    private const page = 'productionArea';
    private const table = 'visitor';
    private const title = '生产区域登记';

    /**
     * 字段初始化
     */
    public function fieldInit($fun): array
    {
        switch ($fun) {
            default:
                $tr = [
                    'type'          => [
                        'name'  => '类型',
                        'width' => 150,
                    ],
                    'role_type1'          => [
                        'name'  => '提货角色',
                        'width' => 100,
                    ],
                    'role_type2'          => [
                        'name'  => '承包角色',
                        'width' => 100,
                    ],
                    'role_type2_1' => [
                        'name'  => "承包作业人角色",
                        'width' => 150,
                    ],
                    'approach'          => [
                        'name'  => '进场装载',
                        'width' => 200,
                    ],
                    'leaving'  => [
                        'name'  => "离场装载",
                        'width' => 150,
                    ],
                    'idNum'         => [
                        'name'  => '证件号码',
                        'width' => 150,
                    ],
                    'borrowInfo'          => [
                        'name'  => '借用信息',
                        'width' => 150,
                    ],
                    'leaveUnit'          => [
                        'name'  => '来访单位',
                        'width' => 150,
                    ],
                    'name'          => [
                        'name'  => '姓名',
                        'width' => 150,
                    ],
                    'contactTel'          => [
                        'name'  => '联系电话',
                        'width' => 150,
                    ],
                    'carNo'          => [
                        'name'  => '车牌号',
                        'width' => 150,
                    ],
                    'arrivalTime'          => [
                        'name'  => '进场时间',
                        'width' => 150,
                    ],
                    'leaveTime'          => [
                        'name'  => '出场时间',
                        'width' => 150,
                    ],
                    'visitDate'          => [
                        'name'  => '上次安全告知日期',
                        'width' => 150,
                    ],
                    'managerId'          => [
                        'name'  => '接待人',
                        'width' => 150,
                    ],
                    'status'          => [
                        'name'  => '状态',
                        'width' => 150,
                    ],
                    'reason'          => [
                        'name'  => '备注',
                        'width' => 150,
                    ],
                ];
        }
        return $tr;
    }

    /*列表页-查询条件*/
    public function homeOptions($isAsync = true)
    {
        //生成查询表单
        $html = $this->tableShow([
            [
                [
                    "日期" => text(array("name" => "time", 'laydate' => ['type' => 'date', 'range' => '~'])),
//                    "类型" => select(["name" => "type", 'title' => '类型', 'option' => ['提送货','监督检查','设备检修'], 'class' => 'text', "value" => '']),
                    "来访单位：" => text(["name" => "leaveUnit", 'class' => 'text', "value" => '']),
                ],
                [
                    "姓名" => text(array("name" => "name")),
                    "证件号码"     => text(array("name" => "idNum")),
                ],
                [
                    "联系电话"     => text(array("name" => "contactTel")),
                    "接待人"     => text(array("name" => "managerId")),
                ],
            ]
        ]);
        //返回
        if(!$isAsync){
            return $html;
        }else{
            return json_encode(['html'=>$html],320);
        }
    }

    /*列表-查询条件*/
    public function home()
    {
        $html = $this->homeOptions(false);
        //控件
        $button = "";
        if ($this->power(self::page, "edit")) {
            $button .= "<span onclick=\"layer('".self::page."','edit')\" class='spanButton'>新增</span>\n";
        }
        if ($this->power(self::page, "del")) {
            $button .= "<span class='spanButton' onclick=\"layer('{$this->get('cla')}', 'operate', {'act': 'del'})\">删除</span>\n";
        }
//        if ($this->power(self::page, 'import')) {
//            $button .="<span class='spanButton' onclick=\"layer('importTemplate','importFrame',{cla:'".self::page."'})\">导入</span>";
//        }
        if ($this->power(self::page, "export")) {
            $button .="<span class='spanButton' onclick=\"layer('importTemplate','exportFrame',{cla:'".self::page."'})\">导出</span>";
        }
        if ($this->power(self::page, "drill")) {
            $button .= "<span class='spanButton' onclick=\"layer('{$this->get('cla')}', 'operate', {'act': 'drill'})\">批量再教育</span>\n";
        }
        if ($this->power(self::page, "edit")) {
            $button .= "<span onclick=\"layer('" . self::page . "','downloadQrCode')\" class='spanButton'>下载二维码</span>\n";
            $button .= "<span onclick=\"layer('" . self::page . "','leaveQrCode')\" class='spanButton'>下载离厂二维码</span>\n";
        }
        //返回
        return $this->homeFun($this->search($html,layout: 'pop',toolButton: $button));
    }

    /*客户列表-查询结果*/
    public function homeSearch()
    {
        //like查询数组
        $like = array(
            "name" => $this->post('name'),
            "idNum" => $this->post('idNum'),
            "contactTel" => $this->post('contactTel'),
        );
        //全等查询数组
        $equal = array(
            "managerId" => $this->post('managerId'),//状态
        );
        $and = "";
        if ($this->post('arrivalTime')) {
            $and .= self::timeComparison($this->post('arrivalTime'));
        }
        //排序
        $orderBy = $this->listSort(array(
            "search"  => $this->post('list_sort_key') ?: 'time',
            "sort" => $this->post('list_sort') ?: "desc",
            "array"   => array(),
        ));
        //获取查询结果
        $where = search(array("like" => $like, "=" => $equal)) . $and;

        $page = $this->page(array("table" => self::table, "where" => $where, "order" => $orderBy['orderBy']));
        $_SESSION[self::page]['sql'] = $page['fullSql'];
        //获取自定义字段参数
        $installSearch = $this->installSearch();
        $body          = [];
        //表格控件区
        $liButton = array(
            $this->checkAll("listForm", "listId")
        );
        //获取记录
        $url = root . "control/adIndex.html?cla=" . self::page;
        $obj = new \control\performanceScoreClass();
        foreach ($page['array'] as $array) {
            //列表控件
            $dominate = array(
                "box" => array("name" => "listId", "value" => $array['id']),
                "detail" => array("title" => self::title . "详情", "click" => "newIframe('" . self::title . "详情','" . $url . "&fun=detail&id=" . $array['id'] . "')"),
            );
            $liButton[] = $this->dominate($dominate);
            $safety_registration = query('safety_registration',"idNum='$array[idNum]' order by updateTime desc");
            //本行初始化
            $row = [];
            foreach ($installSearch['key'] as $key) {
                switch ($key) {
                    case "managerId":
                        $row[] = $obj->findMember($array['managerId'], 2);
                        break;
                    case "carNo":
                        $row[] = $array['shortName'] . $array['carNo'];
                        break;
                    case "visitDate":
                        $visitDate = date('Y-m-d h:i:s', strtotime($safety_registration['visitDate']));
                        $row[] = $safety_registration['visitDate'] ? $visitDate : '';
                        break;
                    case "status":
                        $row[] = $safety_registration['endVisitDate']  < date("Y-m-d h:i:s") ? '需安全培训': '可放行';
                        break;
                    default:
                        $row[] = isset($array[$key]) && $array[$key] ? $array[$key] : '';
                }
            }
            $body[] = $row;
        }
        //控件
        $button = "";
        //生成页面
        $li = $this->li(array(
            "body" => $body,
            "install" => $installSearch,
            "button" => array("html" => $liButton),
            "orderBySign" => $orderBy,
            "page" => $page['para'],
        ));
        //返回
        $json['html'] = $page['hint'] . $button . "<form name='listForm'>" . $li . "</form>" . $page['button'] . clear;
        return json_encode($json, 320);
    }

    /**
     * 下载二维码
     */
    public function downloadQrCode()
    {
        $obj = new talentPoolClass();
        $url = urlencode($this->root.'control/mProduction.html');
        $html = $obj->generateQr($url,'扫码填写来访登记');
        //返回
        return $this->layer(array("title" => "下载二维码", "height" => 500, 'width' => 900, "html" => $html, "button" => false));
    }

    public function leaveQrCode()
    {
        $obj = new talentPoolClass();
        $url = urlencode($this->root.'control/mLeave.html');
        $html = $obj->generateQr($url,'微信扫码填写离场登记');
        //返回
        return $this->layer(array("title" => "下载二维码", "height" => 500, 'width' => 900, "html" => $html, "button" => false));
    }

    /**
     * 下载模板
     */
    public function downloadModel()
    {
        $templateId = $this->get('templateId');
        if (!$this->power(self::page, 'edit')) {
            $_SESSION['warn'] = '你还没有编辑的权限';
        } else {
            $exampleData[] = ['2021-01-01','张三','13000000000','身份证','500223195512121212','渝A00001','8:00:00','11:00:00','参观','样例数据，导入时请删除本条数据'];
            $excel    = $this->excelHead();
            $fileName = self::title.'导入模板-'. \control\importTemplateClass::getName($templateId).'.xlsx';
            $filePath = $excel->fileName($fileName, 'sheet1');
            $format = new \Vtiful\Kernel\Format($filePath->getHandle());
            $templateField = \control\importTemplateClass::templateField(self::page, 'importFieldInit', id:$templateId);
            $index         = 0;
            foreach ($templateField as $k => $array) {
                if ($array['display']){
                    $backgroundStyle=null;
                    if (\control\importTemplateClass::getIsMustValue($this->importFieldInit(), $array['columnName'])){
                        //必填项判断
                        $backgroundStyle  = $format->background(
                            0xFFC04B
                        )->toResource();
                    }
                    $filePath->insertText(0, $index, $array['aliasName'],'',$backgroundStyle);
                    foreach ($exampleData as $y=>$example){
                        $exampleVal = match ($array['columnName']){
                            '日期'=>$example[0],
                            '姓名'=>$example[1],
                            '联系方式'=>$example[2],
                            '证件类型'=>$example[3],
                            '证件号码'=>$example[4],
                            '车牌号'=>$example[5],
                            '来访时间'=>$example[6],
                            '离开时间'=>$example[7],
                            '来访事由'=>$example[8],
                            '备注'=>$example[9],
                            default=>'',
                        };
                        $filePath->insertText($y+1, $index, $exampleVal);
                    }
                    $index++;
                }
            }

            $text = $this->control['name'] . "下载了来访记录导入模板";
            $this->logText(["type" => self::page, "text" => $text]);
            $this->excelOutPut($filePath,$fileName);
            exit(0);
        }
        header("Location:" . getenv("HTTP_REFERER"));
    }

    /*数据导入分析*/
    public function importData()
    {
        $templateId = $this->post('templateId');
        if (!$this->power(self::page, 'edit')) {
            $json['warn'] = '你还没有编辑的权限';
        }   else {
            $fomatArray = [];//导入数据格式同一为TYPE_STRING
            foreach ($this->importFieldInit() as $value){
                $fomatArray[] = \Vtiful\Kernel\Excel::TYPE_STRING;
            }
            $data = $this->importHead(format: $fomatArray);
            $x = 0;
            $text = '';
            $headArray = [];
            $row_list=0;
            foreach ($data as $i => $row) {
                $row_list++;
                if ($i==0){
                    $templateField = \control\importTemplateClass::templateField(self::page, 'importFieldInit', id:$templateId);
                    $headArray = \control\importTemplateClass::combinHead($templateField,$row);
                }
                if ($i > 0) {
                    $rowData = formSubArray($row);
                    //只接收模板中选中的字段的值
                    $cell = [];
                    foreach ($headArray as $index=>$headName){
                        $cell[$headName] = $rowData[$index]??'';
                    }
                    //初始化未被模板需要的字段的值
                    foreach ($this->importFieldInit() as $value){
                        $cell[$value['columnName']] = $cell[$value['columnName']]??'';
                    }
                    $cell['日期'] = self::importDateFormat($cell['日期']);
                    $shortName = mb_substr($cell['车牌号'], 0, 1, 'utf8');
                    $carNo = mb_substr($cell['车牌号'], 1);
                    $field = array(
                        "id" => self::getId(),
                        'stid' => $this->control['stid'],
                        'shortName' => $shortName,
                        'carNo' => $carNo,
                        'visitDate' => $cell['日期'],
                        'name' => $cell['姓名'],
                        'contactTel' => $cell['联系方式'],
                        'type' => $cell['证件类型'],
                        'idNum' => $cell['证件号码'],
                        'arrivalTime' => $cell['来访时间'],
                        'leaveTime' => $cell['离开时间'],
                        'reason' => $cell['来访事由'],
                        'text' => $cell['备注'],
                        'updateTime' => $this->time,
                        "time" => date("Y-m-d H:i:s"),
                    );
                    $userNo = \control\codeTemplateClass::generateCode(self::page,[
                        'prefix' => 'LFDJ',
                        'table' => self::table,
                        'field' => 'orderNo',
                        'where' => '',
                    ],$field);
                    $field['orderNo'] = $userNo;

                    $annotation = [
                        'visitDate' => '日期',
                        'name' => '姓名',
                        'contactTel' => '联系方式',
                        'arrivalTime' => '来访时间',
                        'reason' => '来访事由',
                    ];
                    $rules = [
                        'visitDate' => 'required',
                        'name' => 'required',
                        'contactTel' => 'required',
                        'arrivalTime' => 'required',
                        'reason' => 'required',
                    ];
                    // 校验是否符合规则
                    $vt = new \verify();
                    $result = $vt->setAliases($annotation)->validate($field, $rules)->isOk();
                    if ($result === false) {
                        $text .= "第【{$row_list}】行：" . $vt->getErrs()[0] . "<br>";  // 多个规则提示最前面一条
                    } else {
                        $warn = insert(["table" => self::table, "field" => $field]);
                        if (in_array($warn, ["新增成功", "更新成功"])) {
                            $x++;
                            $text .= "第【{$row_list}】行导入成功<br>";
                        } else {
                            $text .= "第【{$row_list}】导入失败：编辑失败<br>";
                        }
                    }
                }
            }
            $total = count($data)-1;
            $json['data'] = [
                'text'=>$text,
                'title'=>"您导入了{$total}条数据，成功{$x}条，失败".($total-$x)."条",
            ];
            $text = $this->control['name'] . '导入了文件：' . $_FILES['file']['name'] . '：' . $text;
            $this->logText(["type" => self::page, "text" => $text]);
            $json['warn'] = 2;
        }
        return json_encode($json,320);
    }


    /**
     * 导出
     */
    public function exportData()
    {
        $templateId = $this->get('templateId');
        $checkedId = $this->get('checkedId')?explode(',',$this->get('checkedId')):[];
        if (!$this->power(self::page, 'export')) {
            $_SESSION['warn'] = '你还没有导出的权限';
        }  else {
            $obj = new \control\performanceScoreClass();
            $data = [];
            /***********标题**********/
            $title =[];
            $tempFieldAll = \control\importTemplateClass::templateField(self::page, 'exportFieldInit', id:$templateId);
            foreach ($tempFieldAll as $array) {
                if ($array['display']){
                    $title[] = $array['aliasName'];
                }
            }
            //判断是否选中导出
            if (!self::is_null_array($checkedId)){
                $result = find(array(
                    "table" => self::table,
                    "where" => "id in ('".implode("','", $checkedId)."') order by time desc",
                ))['array'];
            }else{
                $sql   = $_SESSION[self::page]['sql'];
                $result   = sqlFind($sql);
            }
            //导出数据生成
            foreach ($result as $array){
                $column = [];
                foreach ($tempFieldAll as $templateField){
                    if ($templateField['display']){
                        $column[] = match ($templateField['columnName']){
                            '单据编号'=>$array['orderNo'],
                            '日期'=>$array['visitDate'],
                            '姓名'=>$array['name'],
                            '联系方式'=>$array['contactTel'],
                            '证件类型'=>$array['type'],
                            '证件号码'=>$array['idNum'],
                            '车牌号'=>$array['shortName'] . $array['carNo'],
                            '来访时间'=>$array['arrivalTime'],
                            '离开时间'=>$array['leaveTime'],
                            '来访事由'=>$array['reason'],
                            '接待人'=> $obj->findMember($array['managerId'], 2),
                            '备注'=>$array['text'],
                            '创建人'=>self::findStaff($array['stid']),
                            '创建时间'=>$array['time'],
                            default=>'',
                        };
                    }
                }
                $data[] = $column;
            }
            $text = $this->control['name'] . "导出了来访记录";
            $this->logText(["type" => self::page, "text" => $text]);
            $this->excelOut($title, $data, "来访记录.xlsx");
            exit(0);
        }
        header("Location:" . getenv("HTTP_REFERER"));
    }

    /**
     * 编辑页
     * @return string
     */
    public function edit()
    {
        $id = $this->post('id')?:self::getId();
        $info = query(self::table, " id = '" . $id . "' ");
        //表单
        $html = $this->layerEdit([
            "table" => [
                [
                    must . "日期：" => text(["name" => "time", 'laydate' => [], 'class' => 'text', "value" => $info['time'] ?: $this->time]),
                    must . "类型：" => select(["name" => "type", 'title' => '类型', 'option' => ['提送货','监督检查','承包商'], 'class' => 'text', "value" => $info['type']]),//提送货车牌号必填
                ],
                [
                    must . "提货角色：" => select(["name" => "role_type1", 'title' => '类型', 'option' => ['驾驶员','押运员'], 'class' => 'text', "value" => '']),
                    must . "承包角色：" => select(["name" => "role_type2", 'title' => '类型', 'option' => ['承包负责人','承包作业人'], 'class' => 'text', "value" => '']),
                ],
                [
                    must . "承包作业人角色：" => select(["name" => "role_type2_1", 'title' => '类型', 'option' => ['辅工','电工证','焊工证','高处作业证','叉车证','动火作业'], 'class' => 'text', "value" => '','multiple'=>true]),
                ],
                [
                    //车牌号必填
                    must . "进场装载：" => text(["name" => "approach", 'class' => 'text', "value" => $info['idNum']]),
                    must . "离场装载：" => text(["name" => "leaving", 'class' => 'text', "value" => $info['idNum']]),
                ],
                [
                    "离厂物料：" => select(["name" => "leaving_material", 'title' => '类型', 'option' => ['空瓶','液氨','氨水'], 'class' => 'text', "value" => $info['leaving_material']]),
                    "100L钢瓶：" => text(["name" => "one_hundred_l", 'class' => 'text', "value" => $info['one_hundred_l']]),
                ],
                [
                    "400L钢瓶：" => text(["name" => "four_hundred_l", 'class' => 'text', "value" => $info['four_hundred_l']]),
                    "800L钢瓶：" => text(["name" => "eight_hundred_l", 'class' => 'text', "value" => $info['eight_hundred_l']]),
                ],
                [
                    must . "证件号码：" => text(["name" => "idNum", 'class' => 'text', "value" => $info['idNum']]),
                    must . "借用信息：" => select(["name" => "borrowInfo", 'title' => '借用信息', 'option' => ['安全帽','定位卡','劳保鞋','工作服'], 'class' => 'text', "value" => $info['borrowInfo']]),
                ],
                [
                    must . "来访单位：" => text(["name" => "leaveUnit", 'class' => 'text', "value" => $info['leaveUnit']]),
                    must . "姓名：" => text(["name" => "name", 'class' => 'text', "value" => $info['name']]),
                ],
                [
                    must . "联系电话：" => text(["name" => "contactTel", 'class' => 'text', "value" => $info['contactTel']]),
                    "车牌号：" => select(["name" => "shortName", 'title' => '车牌号', 'option' => explode('，', para('shortNameOption')), "value" => $info['shortName']]) . text(["name" => "carNo", 'class' => 'text', "value" => $info['carNo']]),
                ],
                [
                    must . "进场时间：" => text(["name" => "arrivalTime",'laydate'=>[], 'class' => 'text', "value" => $info['arrivalTime']]),
                    "出场时间：" => text(["name" => "leaveTime",'laydate'=>[], 'class' => 'text', "value" => $info['leaveTime']]),
                ],
                [
                    "上次安全告知日期：" => text(["name" => "visitDate", 'class' => 'text','laydate'=>[], "value" => $info['visitDate']]),
                    "接待人：" => selectMultiple(["name" => "managerId", 'title' => '接待人', 'table' => "staff", 'sqlId' => 'stid', 'sqlField' => 'name', 'class' => 'text', "value" => $info['managerId']]),
                ],
                [
                    "来访事由：" => textarea(["name" => "reason", 'class' => 'textarea', "value" => $info['reason']]),
                    "进场检查：" => textarea(["name" => "inspect", 'class' => 'textarea', "value" => $info['inspect']]),
                ],
                [
                    "<div class='small-title'>附件</div>" .
                    fileUploadClass::addFileComponent($info['id'], '来访登记', self::page, self::page . 'EditForm')
                ],
            ],
        ]);
        //返回
        return $this->layer(array("title" => L('job.button.editor').self::title, "height" => 500, "html" => $html));
    }

    public function editEdit()
    {
        $id = $this->post('id') ?: self::getId();
        $field = [
            'time' => $this->post('time'),
            'type' => $this->post('type'),
            'role_type1' => $this->post('role_type1'),
            'role_type2' => $this->post('role_type2'),
            'role_type2_1' => $this->post('role_type2_1'),
            'approach' => $this->post('approach'),
            'leaving' => $this->post('leaving'),
            'idNum' => $this->post('idNum'),
            'borrowInfo' => $this->post('borrowInfo'),
            'leaveUnit' => $this->post('leaveUnit'),
            'name' => $this->post('name'),
            'contactTel' => $this->post('contactTel'),
            'shortName' => $this->post('shortName'),
            'arrivalTime' => $this->post('arrivalTime'),
            'leaveTime' => $this->post('leaveTime'),
            'visitDate' => $this->post('visitDate'),
            'reason' => $this->post('reason'),
            'managerId' => $this->post('managerId'),
            'inspect' => $this->post('inspect'),
            'leaving_material' => $this->post('leaving_material'),
            'one_hundred_l' => $this->post('one_hundred_l'),
            'four_hundred_l' => $this->post('four_hundred_l'),
            'eight_hundred_l' => $this->post('eight_hundred_l'),
            'updateTime' => $this->time
        ];
        $fileIdArr = $this->post('fileId');

        $annotation = [
            'type' => '类型',
            'idNum' => '证件号码',
            'borrowInfo' => '借用信息',
            'leaveUnit' => '来访单位',
            'name' => '姓名',
            'contactTel' => '联系电话',
            'arrivalTime' => '来访时间',
            'reason' => '来访事由',
        ];
        $rules = [
            'type' => 'required',
            'idNum' => 'required',
            'borrowInfo' => 'required',
            'leaveUnit' => 'required',
            'name' => 'required',
            'contactTel' => 'required',
            'arrivalTime' => 'required',
            'reason' => 'required',
        ];
        // 校验是否符合规则
        $vt = new \verify();
        $result = $vt->setAliases($annotation)->validate($field, $rules)->isOk();
        if ($result === false) {
            $json['warn'] = $vt->getErrs()[0];  // 多个规则提示最前面一条
            goto resp;
        }
        //判断
        if (!$this->power(self::page, "edit")) {
            $json['warn'] = "你没有编辑" . self::title . "的权限";
        } else {
            $where = " id = '$id' ";
            $info = query(self::table, $where);
            if (!$info['id']) {
                $field = array_merge($field, [
                    'id' => $id,
                    'time' => $this->time
                ]);
                $json['warn'] = static::insert(["table" => self::table, "field" => $field]);
            } else {
                $json['warn'] = static::update([
                    "table" => self::table,
                    "field" => $field,
                    "where" => $where
                ]);
            }
            if (in_array($json['warn'], ["新增成功", "更新成功"])) {
                //添加主表ID到附件表
                if (is_array($fileIdArr)) {
                    update(array('table' => 'file', 'field' => ['targetId' => $id], 'where' => " targetId = '' and id in ('" . implode("','", $fileIdArr) . "')"));
                }
                //添加日志
                $type = mb_substr($json['warn'], 0, 2, 'utf-8');
                $text = $this->control['name'] . $type . "了" . self::title . " id：【" . $id . '】';
                $this->logText(["type" => self::page, "text" => $text]);
                //返回
                $_SESSION['warn'] = $json['warn'];
                $json['warn'] = 2;
                $json['href'] = root . "control/adIndex.html?cla=" . $this->get('cla') . "&fun=detail&id=" . $id;
            }
        }

        resp:
        return json_encode($json, 320);
    }

    /*详情页*/
    public function detail(): string
    {
        $info = query(self::table, " id = '{$this->get('id')}'");
        if (empty($info['id'])) {
            $html = '未找到此' . self::title;
        } else {
            //菜单
            $data = array(
                "id" => $info['id'],
                "title" => self::title . '详情',
            );

            $button = [];
            if ($this->power(self::page, "edit")) {
                //按钮
                $button[] = [
                    "name" => "编辑",
                    "type" => "弹出层",
                    "cla" => $this->get('cla'),
                    "fun" => "edit",
                    "post" => ["id" => $info['id']],
                    'style' => 'li-btn-blue-bg',
                ];
                //按钮
                $button[] = [
                    "name" => "删除",
                    "type" => "弹出层",
                    "cla" => $this->get('cla'),
                    "fun" => "operate",
                    "post" => ["act" => 'del', "id" => $info['id']],
                ];

            }
            $obj = new \control\performanceScoreClass();
            $safety_registration = query('safety_registration', " idNum = '$info[idNum]'");
            //生成表单
            $fileCollection = fileUploadClass::showFile($info['id'], '来访登记');
            $data['button'] = $this->tableShowButton($button);
            $data['html'] = $this->tableShow(array(
                "详细信息" => array(
                    array(
                        "日期" => $info['time'],
                        "类型" => $info['type'],
                        "提货角色" => $info['role_type1'],
                        "承包角色" => $info['role_type2'],
                    ),
                    array(
                        "承包作业人角色" => $info['role_type2_1'],
                        "进场装载" => $info['approach'],
                        "离场装载" => $info['leaving'],
//                        "离场装载" => $info['leaving'] . $info['carNo'],
                        "证件号码" => $info['idNum'],
                    ),
                    array(
                        "借用信息" => $info['borrowInfo'],
                        "来访单位" => $info['leaveUnit'],
                        "姓名" => $info['name'],
                        "联系电话" => $info['contactTel'],
                    ),
                    array(
                        "车牌号" => $info['shortName']. $info['carNo'],
                        "进场时间" => $info['arrivalTime'],
                        "出场时间" => $info['leaveTime'],
                        "上次安全告知日期" => $safety_registration['visitDate'],
                    ),
                    array(
                        "接待人" => $obj->findMember($info['managerId'], 2),
                        "来访事由" => $info['reason'],
                        "进场检查" => $info['inspect'],
                    ),
                ),
                '附件' => array(
                    array(
                        $fileCollection
                    ),
                )
            ));
            //生成页面
            $html = $this->tab($data);
        }
        //返回
        return $html;
    }



    // 操作中转
    public function operate()
    {
        $act = $this->post('act') ?? '';
        $pwd = false; // 需要密码
        $word = false;
        $form = $power = '';
        switch ($act) {
            case 'drill':
                $act      = 'drill';
                $msg      = '培训';
                $title    = '是否确认已培训，确认后将不可修改？';
                $function = 'drillEdit';
                $form     = 'listForm';
                $word     = true;
                break;
            default:
                $act = 'del';
                $msg = '删除' . self::title;
                $title = self::page. 'Delete';
                $function = 'delete';
                $form = self::page . 'OperateForm, listForm';
                $power = '';
                break;
        }
        if (!$this->power(self::page, $act)) {
            $_SESSION['warn'] = '你还没有' . $msg . '的权限';
            $json = [
                'warn' => 2,
                'href' => root . 'control/adIndex.html?cla=' . $this->get('cla') . '&fun=home',
            ];
        } else {
            return $this->confirm([
                'title' => $title,
                'function' => $function,
                'form' => $form,
                'power' => $power,
                'pwd' => $pwd,
                'word' => $word,
            ]);
        }

        resp:
        return json_encode($json, 320);
    }

    /**
     * 培训状态修改
     * @return false|string
     */
    public function drillEdit()
    {
        $array = $this->post('listId') ?? $this->post('id');
        if (!$this->power(self::page, "drill")) {
            $json['warn'] = "你没有培训的权限";
        } elseif (empty($array)) {
            $json['warn'] = "你一个数据都没有选择呢";
        } else {
            $text = "";
            $x = 0;
            $array = is_array($array) ? $array : [$array];
            foreach ($array as $id) {
                $info = query(self::table, " id = '$id' ");
                update(array("table" => self::table,"field"=>['visitDate'=>$this->date], "where" => " id = '$id' "));
                //返回
                $warn = "培训成功";
                $x++;
                $text .= self::title . "ID【" . $info['id'] . "】" . $warn . "。<br>";
            }
            //添加日志
            $text = $this->control['name'] . "培训了" . self::title . "，结果如下：<br>" . $text;
            $this->logText(array("type" => self::page, "text" => $text));
            $_SESSION['warn'] = "培训了" . $x . "个" . self::title . "，详情见系统日志。";
            $json['warn'] = 2;
            $json['href'] = root . "control/adIndex.html?cla=" . $this->get('cla') . "&fun=home";
        }
        return json_encode($json, 320);

    }

    /**
     * 删除
     * @return bool|string
     */
    public function delete()
    {
        $array = $this->post('listId') ?? $this->post('id');
        if (!$this->power(self::page, "del")) {
            $json['warn'] = "你没有删除的权限";
        } elseif (empty($array)) {
            $json['warn'] = "你一个数据都没有选择呢";
        } else {
            $text = "";
            $x = 0;
            $array = is_array($array) ? $array : [$array];
            foreach ($array as $id) {
                $info = query(self::table, " id = '$id' ");

                //最后删除基本参数
                delete(array("table" => self::table, "where" => " id = '$id' "));
                //返回
                $warn = "删除成功";
                $x++;

                $text .= self::title . "ID【" . $info['id'] . "】" . $warn . "。<br>";
            }
            //添加日志
            $text = $this->control['name'] . "删除了" . self::title . "，结果如下：<br>" . $text;
            $this->logText(array("type" => self::page, "text" => $text));
            $_SESSION['warn'] = "删除了" . $x . "个" . self::title . "，详情见系统日志。";
            $json['warn'] = 2;
            $json['href'] = root . "control/adIndex.html?cla=" . $this->get('cla') . "&fun=home";
        }
        return json_encode($json, 320);
    }

    /**
     * 导入模板字段初始化
     * @return array[]
     */
    public function importFieldInit($classify=''): array
    {
        return match ($classify) {
            default=>  [
                [
                    'columnName'=>'日期',
                    'aliasName'=>'日期',
                    'isMust'=>true,
                ],
                [
                    'columnName'=>'姓名',
                    'aliasName'=>'姓名',
                    'isMust'=>true,
                ],
                [
                    'columnName'=>'联系方式',
                    'aliasName'=>'联系方式',
                    'isMust'=>true,
                ],
                [
                    'columnName'=>'证件类型',
                    'aliasName'=>'证件类型',
                    'isMust'=>false,
                ],
                [
                    'columnName'=>'证件号码',
                    'aliasName'=>'证件号码',
                    'isMust'=>false,
                ],
                [
                    'columnName'=>'车牌号',
                    'aliasName'=>'车牌号',
                    'isMust'=>false,
                ],
                [
                    'columnName'=>'来访时间',
                    'aliasName'=>'来访时间',
                    'isMust'=>true,
                ],
                [
                    'columnName'=>'离开时间',
                    'aliasName'=>'离开时间',
                    'isMust'=>false,
                ],
                [
                    'columnName'=>'来访事由',
                    'aliasName'=>'来访事由',
                    'isMust'=>true,
                ],
                [
                    'columnName'=>'备注',
                    'aliasName'=>'备注',
                    'isMust'=>false,
                ],
            ]
        };
    }

    /**
     * 导出模板字段初始化
     * @return array[]
     */
    public function exportFieldInit($classify=''): array
    {
        return match ($classify) {
            default=>  [
                [
                    'columnName'=>'单据编号',
                    'aliasName'=>'单据编号',
                ],
                [
                    'columnName'=>'日期',
                    'aliasName'=>'日期',
                ],
                [
                    'columnName'=>'姓名',
                    'aliasName'=>'姓名',
                ],
                [
                    'columnName'=>'联系方式',
                    'aliasName'=>'联系方式',
                ],
                [
                    'columnName'=>'证件类型',
                    'aliasName'=>'证件类型',
                ],
                [
                    'columnName'=>'证件号码',
                    'aliasName'=>'证件号码',
                ],
                [
                    'columnName'=>'车牌号',
                    'aliasName'=>'车牌号',
                ],
                [
                    'columnName'=>'来访时间',
                    'aliasName'=>'来访时间',
                ],
                [
                    'columnName'=>'离开时间',
                    'aliasName'=>'离开时间',
                ],
                [
                    'columnName'=>'来访事由',
                    'aliasName'=>'来访事由',
                ],
                [
                    'columnName'=>'接待人',
                    'aliasName'=>'接待人',
                ],
                [
                    'columnName'=>'备注',
                    'aliasName'=>'备注',
                ],
                [
                    'columnName'=>'创建人',
                    'aliasName'=>'创建人',
                ],
                [
                    'columnName'=>'创建时间',
                    'aliasName'=>'创建时间',
                ],
            ]
        };
    }
}

